<template>
  <div class="login-container">
    <div class="login_background_front">

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">
          <img class="logo" src="@/assets/login_images/logo.png" />
          {{$t('Lumiere Cafe')}}
        </h3>
      </div>

      <el-tabs value="first">
        <el-tab-pane label="账号密码" name="first">
          <span slot="label"><i class="el-icon-user"></i> {{$t('账号密码')}}</span>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" v-model="loginForm.username" name="username" type="text" auto-complete="on" :placeholder="$t('账号')" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" type="password" show-password v-model="loginForm.password" name="password" auto-complete="on" :placeholder="$t('密码')"  />
          </el-form-item>

          <el-form-item prop="captchaCanvas">
            <canvas ref="captchaCanvas" @click="refreshCaptcha"></canvas>
            <el-input prefix-icon="el-icon-share" style="width: 200px;float: right" type="text" v-model="captchaInput"  :placeholder="$t('验证码')"  />
          </el-form-item>

          <el-button icon="el-icon-s-promotion" :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">{{$t('登录')}}</el-button>
        </el-tab-pane>
        <el-tab-pane label="手机｜邮箱" name="second">
          <span slot="label"><i class="el-icon-mobile"></i> {{$t('手机')}}｜<i class="el-icon-message"></i> {{$t('邮箱')}}</span>
          <el-form-item prop="mobOremail">
            <el-input prefix-icon="el-icon-edit-outline" v-model="loginForm.mobOremail" name="username" type="text" auto-complete="on" :placeholder="$t('手机或邮箱')" />
          </el-form-item>

          <el-form-item prop="authCode">
            <el-input prefix-icon="el-icon-share" style="width: 50%" v-model="loginForm.authCode" name="authCode" auto-complete="on" :placeholder="$t('验证码')" @keyup.enter.native="handleLogin" />
            <el-button
              icon="el-icon-position"
              class="send-code"
              @click.stop="sendVerificationCode"
              size="mini"
              type="primary"
              v-if="show">{{$t('发送验证码')}}</el-button>
            <el-button
              plain1
              icon="el-icon-position"
              class="send-code"
              size="mini"
              type="primary"
              v-if="!show"
              disabled>{{ count }}{{$t('秒后重发')}}</el-button>
          </el-form-item>

          <el-button icon="el-icon-s-promotion" :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleMobOremailLogin">{{$t('登录')}}</el-button>
        </el-tab-pane>
      </el-tabs>


      <div style="position:relative;margin-top: 50px;" align="center">
        <el-link style="font-size: 15px" href="http://www.yliyun.com" type="primary" target="_blank">{{$t('由深圳一粒云科技有限公司提供技术支持')}}</el-link>
      </div>
      <h5>
         <template>
          <el-tooltip :content="$t('Layout_size')" effect="dark" placement="bottom">
            <size-select class="international right-menu-item"/>
          </el-tooltip>

          <el-tooltip :content="$t('语言选择')" effect="dark" placement="bottom">
            <language-select class="international right-menu-item"/>
          </el-tooltip>
        </template>
      </h5>
    </el-form>
    </div>
  </div>
</template>

<script>
  import IconUploader from '@/components/IconUploader'
  import { sendAuthCode ,getUserInfo} from '@/api/login'
  import SizeSelect from '@/components/SizeSelect'
  import LanguageSelect from '@/components/LanguageSelect'
  import Hamburger from "../../components/Hamburger/index.vue";
export default {
  name: 'Login',
  components: {
    Hamburger,
    IconUploader,
    SizeSelect,
    LanguageSelect
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error(this.$t('管理员密码长度应大于6')))
      } else {
        callback()
      }
    }
    return {
      captchaInput: '',
      captchaCanvas: '',
      btnText: "获取验证码",
      show: true,
      count: "",
      timer: null,
      loginForm: {
        username: '',
        password: '',
        mobOremail:'',
        authCode:''
      },
      loginRules: {
        username: [{ required: true, message: this.$t('Controller_ID_cannot_be_empty'), trigger: 'blur' }],
        password: [
          { required: true, message: this.$t('Controller_password_cannot_be_empty'), trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        authCode:[{ required: true, message: this.$t('请填写验证码'), trigger: 'blur' }],
        mobOremail:[{ required: true, message: this.$t('请填写手机或邮箱'), trigger: 'blur' }]
      },
      passwordType: 'password',
      loading: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }

  },
  mounted() {
    this.refreshCaptcha();
    window.addEventListener("resize", this.handleResize);
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
  },
  destroyed() {
    window.removeEventListener("resize", this.handleResize);
    // window.removeEventListener('hashchange', this.afterQRScan)
  },
  methods: {
    handleResize() {
      const windowHeight = window.innerHeight;
      if (windowHeight < 600) { // 说明键盘弹出了（600px 可调整）
        document.body.style.height = `${windowHeight}px`; // 让页面适应键盘
      } else {
        document.body.style.height = "100vh"; // 复原
      }
    },
    refreshCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = canvas.getContext('2d');

      // 设置Canvas的宽度和高度
      canvas.width = 230; // 清空画布，重置宽度
      canvas.height = 40; // 设置高度为80px

      // 生成随机验证码字符串
      const captchaText = this.generateCaptchaText();
      this.captchaCanvas=captchaText

      //测试的时候可以打开，免输入验证码
      this.captchaInput=captchaText


      // 绘制验证码文本
      ctx.font = '24px Arial';
      ctx.fillText(captchaText, 10, 30);

      // 绘制干扰线
      for (let i = 0; i < 5; i++) {
        this.drawRandomLine(ctx, canvas.width, canvas.height);
      }

      // 绘制干扰点
      for (let i = 0; i < 30; i++) {
        this.drawRandomPoint(ctx, canvas.width, canvas.height);
      }
    },

    generateCaptchaText() {
      // 生成随机验证码字符串，例如包含数字和大写字母的组合
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let captchaText = '';
      for (let i = 0; i < 6; i++) {
        captchaText += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return captchaText;
    },
    drawRandomLine(ctx, canvasWidth, canvasHeight) {
      // 绘制随机干扰线
      const startX = Math.random() * canvasWidth;
      const startY = Math.random() * canvasHeight;
      const endX = Math.random() * canvasWidth;
      const endY = Math.random() * canvasHeight;

      ctx.beginPath();
      ctx.moveTo(startX, startY);
      ctx.lineTo(endX, endY);
      ctx.strokeStyle = '#999';
      ctx.stroke();
    },
    drawRandomPoint(ctx, canvasWidth, canvasHeight) {
      // 绘制随机干扰点
      const x = Math.random() * canvasWidth;
      const y = Math.random() * canvasHeight;

      ctx.beginPath();
      ctx.arc(x, y, 1, 0, 2 * Math.PI);
      ctx.fillStyle = '#999';
      ctx.fill();
    },


    handleLogin() {
      if(this.loginForm.username!=''&&this.loginForm.password!='') {
        // 验证用户输入的验证码
        const userInput = this.captchaInput.toUpperCase(); // 将输入的验证码转换为大写;
        const captchaText = this.captchaCanvas.toUpperCase(); // 将输入的验证码转换为大写;

        if (userInput === captchaText) {
          // 验证通过，执行登录操作或其他操作

        } else {
          // 验证失败，提示用户重新输入验证码
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('The verification code fails. Procedure')
          })
          // 清空输入框
          this.captchaInput = '';
          // 刷新验证码
          this.refreshCaptcha();
          return;
        }

        if ( !this.loading) {
          this.loading = true
          this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
            this.loading = false
            this.$router.push({ path: this.redirect || '/' })
          }).catch(response => {
            this.loading = false
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t(response.data.errmsg)
            })
          })
        } else {
          return false
        }
      }
    },
    handleMobOremailLogin(){
      if(this.loginForm.mobOremail!=''&&this.loginForm.authCode!='') {
        this.loading = true
        this.$store.dispatch('LoginByMobOremail', this.loginForm).then(() => {
          this.loading = false
          this.$router.push({ path: this.redirect || '/' })
        }).catch(response => {
          this.loading = false
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
      }else {
        this.$notify({
          title: this.$t('警告'),
          message: this.$t('请填写手机或邮箱'),
          type: 'warning'
        });
        this.loading = false
        return false
      }
    },
    //验证码 倒计时
    sendVerificationCode() {
      if(this.loginForm.mobOremail==''){
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t('请填写手机或邮箱')
        })
      } else {
        this.loginForm.authCode=''
        let TIME_COUNT = 60;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000);
          this.getCode();
        }
      }
    },
    getCode(){
      sendAuthCode(this.loginForm.mobOremail).then(res=>{
        this.$notify.success({
          title: this.$t('成功'),
          message: this.$t('验证码发送成功')
        })
      }).catch(res => {
        this.$notify.warning({
          title: this.$t('失败'),
          message: this.$t('账号不存在')
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg:#2d3a4b;
$light_gray: #202124;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
  }

}

</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray: #3086bd;
.login_background_front {
  width: 450px;
  height: 450px;
  margin-left: 100px;
  margin-top: 13%;
  overflow: hidden;
  /*position: relative;*/
  background-size: cover;
  background-position: center;
  background-image: url(../../../static/tinymce4.7.5/skins/lightgray/img/login_background_front.png) ;
  animation-name: myfirst;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 1s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-play-state: running;
}
.login-container {
  height: 100%;
  width: 100%;
  background: url("../../../static/tinymce4.7.5/skins/lightgray/img/login_background.png") no-repeat $bg;
  background-size:cover;
  //background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 520px;
    padding: 35px 35px 15px 35px;
    margin: auto 55%;
    //border: #dcd7d7 1px solid;
    border-radius: 12px;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    &_login {
      font-size: 20px;
    }
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      line-height: unset;
    }
  }
  .send-code{
    position: absolute;
    right: 1px;
    border-radius: 0px;
  }
  .logo{
    height:66px;
    width:70px;
    margin-right: 2%;
    vertical-align:middle;
  }
  h5{
    text-align:right;
  }
}
</style>
